<template>
    <div class="login">
        <form v-if="page === PAGETYPE.LOGIN">
            <h1>登录</h1>
            <label>
                <span>密码</span>：
                <input class="base-input" type="password" v-model="password"/>
            </label>

            <label style="display: flex; ">
                <button class="base-button" @click.prevent="login">登录</button>
                <button class="base-button exit" @click.prevent="exit">退出</button>
            </label>

            <label class="options">
                <a @click="adminOpt">管理员重置</a>
            </label>
        </form>

        <form v-if="page === PAGETYPE.RESET">
            <div class="back" @click="back">返回</div>
            <h1>重置密码</h1>

            <label>
                <span>管理员密码</span>：
                <input class="base-input" type="password" v-model="superPassword"/>
            </label>
            <label>
                <span>设备密码</span>：
                <input class="base-input" type="password" v-model="resetPassword"/>
            </label>

            <label>
                <button class="base-button" @click.prevent="resetEvent">确定</button>
            </label>
        </form>


    </div>
</template>

<script>
    import {IO} from "../common/plus/io";
    import {md5} from "$common/md5";
    import {DeleteDB} from "../common/data-base/DataInterface";

    export default {
        name: "Login",
        data() {
            return {
                PAGETYPE: {
                    LOGIN: 1,
                    RESET: 2
                },
                page: 1,
                password: '',
                superPassword: '',
                resetPassword: '',
                errorCount: 0
            }
        },
        created() {
            this.page = this.PAGETYPE.LOGIN;
        },
        computed: {
            passwordMD5() {
                return md5(this.password);
            },
            superPasswordMD5() {
                return md5(this.superPassword);
            },
            resetPasswordMD5() {
                return md5(this.resetPassword);
            }
        },
        methods: {
            login() {
                if (this.$production) {
                    IO.fileExist('test.db', '_doc/').then(exist => {
                        if (exist) {
                            if (this.$store.state.passwordModule.devicePassword === this.passwordMD5) {
                                this.$router.push('/home');
                            } else {
                                this.passwordError(this.errorCount);
                            }
                        } else {
                            alert('本机数据不存在或已被清除，请即时联系管理员');
                            plus.runtime.quit();
                        }
                    });
                } else {
                    this.$router.push('/home');
                }
            },
            adminOpt() {
                this.page = this.PAGETYPE.RESET;
            },
            passwordError(count) {
                count = count ? count : 0;
                count += 1;
                this.errorCount = count;
                console.log(`密码第${count}次输入失败`);
                if (count > 2 && count < 5) {
                    alert(`您的密码已连续错误${count}次，还有${5 - count}次机会`);
                } else if (count === 5) {
                    alert(`您的密码已连续错误${count}次，本机数据已被清除，请即时联系管理员`);
                    this.cleanData();
                } else {
                    alert('密码错误');
                }
            },
            // 清除数据
            cleanData() {
                DeleteDB().then(() => {
                    IO.removeFile('_doc/test.db', (path) => {
                        console.log(`'${path}'已清除`);
                    });
                    IO.removeDirectory('_documents/photos', (path) => {
                        console.log(`'${path}'已清除`);
                    });
                });
            },
            resetEvent() {
                if (this.$production) {
                    if (this.$store.state.passwordModule.superPassword !== this.superPasswordMD5) {
                        alert('管理员密码错误');
                        return;
                    }
                    if (this.resetPassword.length < 6) {
                        alert('设备密码大于6位');
                        return;
                    }

                    if (this.$store.state.plusAlready) {
                        IO.writeFile('password.json', ({data, writer, error, mes}) => {
                            if (!error) {
                                if (data) {
                                    let param = data;
                                    param["devicePassword"] = this.resetPasswordMD5;

                                    writer.onwrite = () => {
                                        this.$store.commit('setDevicePasswor', param.devicePassword);
                                        this.$store.commit('setSuperPasswor', param.superpassword);
                                        alert("修改成功");
                                        this.back();
                                    };
                                    let str = JSON.stringify(param);
                                    writer.seek(0);
                                    writer.write(str);
                                }
                            } else {
                                alert(mes);
                            }
                        });
                    }
                } else {
                    this.back();
                }
            },
            back() {
                this.page = this.PAGETYPE.LOGIN;
            },
            exit() {
                if (this.$store.state.plusAlready) {
                    ('iOS' === plus.os.name) ? plus.nativeUI.confirm('确认退出？', function (e) {
                        if (e.index > 0) {
                            plus.runtime.quit();
                        }
                    }, 'HelloH5', ['取消', '确定']) : (confirm('确认退出？') && plus.runtime.quit());
                } else {
                    console.log('退出');
                }
            }
        }
    };
</script>

<style scoped lang="scss">
    @import "../assets/scss/base";

    .login {
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-image: url("../assets/imgs/home/bg.png");
        background-repeat: no-repeat;
        background-size: cover;
        background-position: top;
        color: $base-color;

        form {
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 250px;
            border: 1px solid $base-color;
            box-shadow: 8px 8px 10px 4px #d3d3d3;
            border-radius: 5px;
            padding: 30px;
            padding-top: 80px;

            .back {
                position: absolute;
                top: 10px;
                left: 15px;
            }

            h1 {
                position: absolute;
                top: 10px;
                left: 50%;
                transform: translateX(-50%);
            }

            label {
                &:not(:last-child) {
                    margin-bottom: 25px;
                }

                span {
                    width: 90px;
                    display: inline-block;
                    text-align: justify;
                    vertical-align: middle;
                    height: 23px;
                    overflow: hidden;

                    &::after {
                        content: '';
                        display: inline-block;
                        width: 100%;
                    }
                }

                input {
                    width: 220px;
                }

                button {
                    width: 100%;
                    height: 35px;
                    color: $base-color;
                    font-size: 16px;
                }

                &.options {
                    text-align: right;

                }
            }
        }

        .exit {
            color: red;
            width: 100px;
            margin-left: 10px;
        }
    }
</style>
